package org.newdawn.slick.util;

import java.io.InputStream;
import java.net.URL;
import java.util.Vector;

/**
 * A resource location that searches the classpath
 * 
 * @author kevin
 */
public class ClasspathLocation implements ResourceLocation {
	private static Vector classList = new Vector();

	static public void addClass(Class c) {
		if (!classList.contains(c))
			classList.add(c);
	}

	/**
	 * @see org.newdawn.slick.util.ResourceLocation#getResource(java.lang.String)
	 */
	public URL getResource(String ref) {
		String cpRef = ref.replace('\\', '/');
		URL url = null;
		for (int i = 0; i < classList.size(); i++) {
			Class c = ((Class) classList.get(i));
			//System.out.println(c.getName()+".getResource "+cpRef);
			Log.info(c.getName()+".getResource "+cpRef);
			url = c.getResource(cpRef);
			if (url != null)
				break;
		}
		if (url == null)
			url = ResourceLoader.class.getClassLoader().getResource(cpRef);
		return url;
	}

	/**
	 * @see org.newdawn.slick.util.ResourceLocation#getResourceAsStream(java.lang.String)
	 */
	public InputStream getResourceAsStream(String ref) {
		String cpRef = ref.replace('\\', '/');
		InputStream stm = null;
		for (int i = 0; i < classList.size(); i++) {
			Class c = ((Class) classList.get(i));
			//System.out.println(c.getName()+".getResource "+cpRef);
			Log.info(c.getName()+".getResource "+cpRef);
			stm = c.getResourceAsStream(cpRef);
			if (stm != null)
				break;
		}

		if (stm == null)
			stm = ResourceLoader.class.getClassLoader().getResourceAsStream(
					cpRef);
		return stm;
	}

}
